<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

/**
 * Class ValidatePrice
 * @package App\Rules
 *
 * 验证价格金额格式是否正确
 */
class ValidatePrice implements Rule
{
    private $isCheck;       // 是否触发此验证规则


    /**
     * Create a new rule instance.
     *
     * ValidatePrice constructor.
     * @param bool $isCheck
     */
    public function __construct($isCheck = true)
    {
        $this->isCheck = $isCheck;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if($this->isCheck) {
            if (!preg_match('/^(\d+)(\.\d{0,2})?$/', $value)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The price is wrong format!';
    }
}
